package com.cssy.yd.logic.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cssy.authority.service.IScDepartmentService;
import com.cssy.authority.service.IScUserRolewhPlaceService;
import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.yd.basic.service.IBasicCompanyService;


import com.cssy.yd.logic.entity.LogicSoDO;
import com.cssy.yd.logic.entity.LogicSoItemDO;
import com.cssy.yd.logic.entity.LogicSoWarefreezeDO;
import com.cssy.yd.logic.entity.LogicSoWarefreezeItemDO;

import com.cssy.yd.logic.service.ILogicSoItemService;

import com.cssy.yd.logic.service.ILogicSoService;
import com.cssy.yd.logic.service.ILogicSoWareItemService;
import com.cssy.yd.logic.service.ILogicSoWareService;
import com.cssy.yd.logic.service.ILogicSoWarefreezeService;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.SessionUtil;
import com.plat.util.json.OutJsonGrid;

/**
 * 销售冻结申请控制器
 * @author huang.xuming [2013-8-23]
 *
 */
@Controller
@RequestMapping("/yd/logic/sowarefreeze")
public class SoWareFreezeController extends BaseController<LogicSoWarefreezeDO> {

	private static final Logger logger = Logger.getLogger(SoWareFreezeController.class);
			
	private static final String MANAGER = "/yd/logic/sowarefreeze/SoWareFreezeManager";// 列表页面
	private static final String EIDT = "/yd/logic/sowarefreeze/SoWareFreezeOperation";// 添加、修改、显示页面
	
	@Resource(name = "logicSoWareService")
	private ILogicSoWareService logicSoWareService;
	@Resource(name = "logicSoService")
	private ILogicSoService logicSoService;
	@Resource(name = "logicSoItemService")
	private ILogicSoItemService logicSoItemService;
	@Resource(name = "logicSoWareItemService")
	private ILogicSoWareItemService logicSoWareItemService;
	@Resource(name = "basicCompanyService")
	IBasicCompanyService basicCompanyService;
	@Resource(name="scUserRolePlaceService")
	private IScUserRolewhPlaceService scUserRolePlaceService;
	
	@Resource(name = "logicSoWarefreezeService")
	private ILogicSoWarefreezeService logicSoWarefreezeService ;

	
	@Resource(name = "scDepartmentService")
    private IScDepartmentService scDepartmentService;
	
	
	@Override
	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		return MANAGER;
	}

	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		hander.getWheres(scs);
		SearchResult result = logicSoWarefreezeService.findListByExample(scs);
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);
	}

	@Override
	public String operationForm(HttpServletRequest request, 
			@PathVariable String id,@PathVariable String flag, Model model) throws Exception {
		
		if (OperationFlag.ADD.equals(flag)) {
			// 新增加时操作
			model.addAttribute("flag", "ADD");
		} else {
			LogicSoWarefreezeDO sowarefreeze = logicSoWarefreezeService.findListById(id);
			//List<LogicSoWarefreezeItemDO> sowareitem = logicSoWarefreezeService.findItemListBysowarefreezeId(sowarefreeze.getId());
			model.addAttribute("flag", "EDIT");
			model.addAttribute("soware", sowarefreeze);
			//model.addAttribute("sowareitem", sowareitem);
			//TODO 获取订单相应出库、冻结信息
		}
		
		//可冻结的销售订单
		//TODO 考虑根据订单明细、出库明细、出库冻结明细结合判断出库状态、冻结状态
		List<LogicSoDO> solist = new ArrayList<LogicSoDO>();
		SearchConditions scsso = new SearchConditions();
		scsso.addCondition("billstatus", "4,5", SearchCondition.OP_IN);// 订单状态-二审完结、三审完结
		scsso.addCondition("ware_status", "0,1", SearchCondition.OP_IN);// 出库状态-非完全出库
		scsso.addCondition("frozen_status", "1", SearchCondition.OP_NOTEQUAL);// 订单库存-非全部冻结 
		scsso.setLimitPage(false);// 不分页
		solist = logicSoService.findListByExample(scsso).getResults();
		
		model.addAttribute("solist", solist);
		
		//部门列表
		model.addAttribute("depts",SoController.getDepartmentList(scDepartmentService));
				
		return EIDT;
	}
	
	@RequestMapping(value = "/griditems")
	public void griditems(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			LogicSoWarefreezeDO sowarefreeze = logicSoWarefreezeService.findListById(id);
			List<LogicSoWarefreezeItemDO> sowareitem = logicSoWarefreezeService.findItemListBysowarefreezeId(sowarefreeze.getId());
			OutJsonGrid out = new OutJsonGrid(sowareitem);
			out.printJSon(response);
		}
	}
	

	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicSoWarefreezeDO curAP, BindingResult result, Model model)
			throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		String itemdata =request.getParameter("itemdata");
		if(StringUtils.isBlank(itemdata)){
			bodyMap.isFail();
			bodyMap.configWebInfor("物料内容不能为空！");
			return bodyMap.modelMap;
		}try {
			logicSoWarefreezeService.soWarefreezeSave(request, curAP);
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
			bodyMap.configWebId(curAP.getId());
		} catch (Exception e) {
			logger.warn(e.getMessage(),e);
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()+ e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String ids = request.getParameter("ids");
			String[] fields=ids.split(",");
			for(String field : fields){
				LogicSoWarefreezeDO ld=logicSoWarefreezeService.findListById(field);
				ld.setRemoved(1);
				logicSoWarefreezeService.update(ld, SessionUtil.getUser(request));
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}
	
//	@RequestMapping("/soitemlist")
//	public void soitemlist(@RequestParam("soNo") String soNo, HttpServletRequest request, HttpServletResponse response){
//		SearchResult result= new SearchResult();
//		LogicSoItemDO bean = new LogicSoItemDO();
//		
//		List<LogicSoItemDO> soitemlist = new ArrayList<LogicSoItemDO>();
//		if(StringUtils.isNotBlank(soNo)){
//			bean.setSoNo(soNo);
//			soitemlist = logicSoItemService.findListByDO(bean);
//		}
//		
//		result.setResults(soitemlist);
//		result.setRecordCount(soitemlist.size());
//		OutJsonGrid out = new OutJsonGrid(result);
//		out.printJSon(response);
//	}
	
	
	/* 驳回操作 */
//	@RequestMapping("/bh")
//	@ResponseBody
//	public Map<String,String > sowarebh(HttpServletRequest request, HttpServletResponse response){
//		Map<String,String > map=new HashMap<String, String>();
//		String id = request.getParameter("id");
//		try{
//			LogicSoWareDO ld=logicSoWareService.findListById(id);
//			if(ld.getId()!=null){
//				if(ld.getBillstatus()!=1||ld.getBillstatus()!=2){
//					ld.setBillstatus(Integer.parseInt("0"));
//					logicSoWareService.update(ld, SessionUtil.getUser(request));
//					map.put("msg", "已驳回到草稿状态！可以继续修改");
//				}else{
//					map.put("msg", "当前状态不可以做驳回操作");
//				}
//			}else{
//				map.put("msg", "没有获取到当前订单的相关信息");
//			}
//		}catch(Exception e){
//			//e.printStackTrace();
//			logger.warn(e.getMessage(),e);
//			map.put("msg", "出现未知错误，请重新操作！");
//		}
//		return map;
//	}
	
	@RequestMapping(value = "/exportExcel")
	public void printer(HttpServletRequest request, HttpServletResponse response) throws Exception{
		//TODO 导出功能
//		try {
//			
//			
//			String id = request.getParameter("id");
//			LogicSoWareDO soware=new LogicSoWareDO();
//			List<LogicSoWareItemDO> lp=new ArrayList<LogicSoWareItemDO>();
//			List<LogicFreightageDO> freightageDOs=new ArrayList<LogicFreightageDO>();
//			if(!"".equals(id)&&id!=null){
//				soware = logicSoWareService.findListById(id);
//			}
//			if(soware.getId()!=null){
//				lp = logicSoWareItemService.findItemListBysowareId(soware.getId());
//				SearchConditions sc = new SearchConditions();
//				sc.setRemovedProperty(null);//判断是否有删除标识
//				sc.addCondition("tid", soware.getId(), SearchCondition.OP_EQUAL);
//				freightageDOs=logicFreightageService.findListByExample(sc).getResults();
//			}
//			if(lp.size()>0){
//				request.setAttribute("soware", soware);
//				request.setAttribute("lp", lp);
//				request.setAttribute("row", lp.size());
//				if(freightageDOs.size()>0){
//					for(int i=0;i<freightageDOs.size();i++){
//						if("铁运费".equals(freightageDOs.get(i).getFreightagename())){
//							request.setAttribute("T", freightageDOs.get(i).getFreightageprice());
//						}
//						if("海运费".equals(freightageDOs.get(i).getFreightagename())){
//							request.setAttribute("H", freightageDOs.get(i).getFreightageprice());
//						}
//						if("短运费".equals(freightageDOs.get(i).getFreightagename())){
//							request.setAttribute("D", freightageDOs.get(i).getFreightageprice());
//						}
//						if("装卸费".equals(freightageDOs.get(i).getFreightagename())){
//							request.setAttribute("Z", freightageDOs.get(i).getFreightageprice());
//						}
//						if("落箱费".equals(freightageDOs.get(i).getFreightagename())){
//							request.setAttribute("L", freightageDOs.get(i).getFreightageprice());
//						}
//						if("其他".equals(freightageDOs.get(i).getFreightagename())){
//							request.setAttribute("Q", freightageDOs.get(i).getFreightageprice());
//						}
//					}
//					
//				}
//				
//				response.setContentType("application/vnd.ms-excel");
//				response.setHeader("Content-disposition", "attachment;filename=export_" + System.currentTimeMillis() + ".xls");
//			
//				RequestDispatcher dispatcher = request.getRequestDispatcher("/views/printer/SoWarePrint.jsp");
//			
//				dispatcher.forward(request, response);
//			}
//		} catch (ServletException e) {
//			e.printStackTrace();
//		}
	}
	
}
